//
//  RegisterViewController.m
//  PPDL
//
//  Created by 王洋 on 2019/7/23.
//  Copyright © 2019 王洋. All rights reserved.
//

#import "AFNetworking.h"

#import "RegisterViewController.h"
#import "UIButton+CountDown.h"

@interface RegisterViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *phoneNumTF;
@property (weak, nonatomic) IBOutlet UITextField *V_CodeTF;
@property (weak, nonatomic) IBOutlet UITextField *pswTF;
@property (weak, nonatomic) IBOutlet UITextField *confirmPswTF;
@property (weak, nonatomic) IBOutlet UITextField *invitationCodeTF;
@property (weak, nonatomic) IBOutlet UILabel *protocolLab;

@property (weak, nonatomic) IBOutlet UIButton *agreeBtn;
@property (weak, nonatomic) IBOutlet UIButton *registerBtn;
@property (weak, nonatomic) IBOutlet UIButton *getVertificationBtn;

@property (nonatomic, assign) BOOL isAgree;

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
}

//已有账号，马上登陆
- (IBAction)goLogin:(id)sender {
    
}

#pragma mark 同意隐私权限
- (IBAction)admire:(id)sender {
    
    [self.view endEditing:YES];
    self.isAgree = !self.isAgree;
    if (!self.isAgree) {
        [self.agreeBtn setImage:[UIImage imageNamed:@"empty_bg"] forState:UIControlStateNormal];
    } else {
        [self.agreeBtn setImage:[UIImage imageNamed:@"admire_bg"] forState:UIControlStateNormal];
    }
}
- (IBAction)backToLogin:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)goHtml {
    
    PPWebViewController * webvc = [[PPWebViewController alloc] init];
    webvc.webUrl = [NSString stringWithFormat:@"%@%@",TT_Global_H5_Domain,TT_HTML_PRIVACY_POLICY];
    [self.navigationController pushViewController:webvc animated:YES];
    
}

#pragma mark 根据手机号获取验证码获取验证码
- (IBAction)getVertificationCode:(id)sender {
    
    if (self.phoneNumTF.text.length) {
        
        if ([Utilities checkPhoneTel:self.phoneNumTF.text]) {
            [self.getVertificationBtn startWithTime:60 title:@"重新获取" countDownTitle:@"s" mainColor:[UIColor whiteColor] countColor:[UIColor whiteColor]];
            
            [self requestV_Code];
            [self.V_CodeTF becomeFirstResponder];
            
        } else {
            [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号"];
            [self.phoneNumTF becomeFirstResponder];
        }

    } else {
        
        [SVProgressHUD showErrorWithStatus:@"请输入手机号"];
        [self.phoneNumTF becomeFirstResponder];
    }
    
    [SVProgressHUD dismissWithDelay:0.5];
}


- (void)requestV_Code {
    
    NSDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.phoneNumTF.text forKey:@"phone"];
    [dic setValue:@"1" forKey:@"type"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_REGISTER_SMSCODE];
    
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        if ([data isKindOfClass:[NSDictionary class]]) {

            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {
                [SVProgressHUD showSuccessWithStatus: [data valueForKey:@"msg"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {

    }];
}

- (void)request_Register {
    
    if (!self.phoneNumTF.text.length) {
        return;
    }
    
    if (!self.pswTF.text.length) {
        return;
    }
    
    if (!self.V_CodeTF.text.length) {
        return;
    }
    
    
    self.registerBtn.userInteractionEnabled = NO;
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.phoneNumTF.text forKey:@"phone"];
    [dic setValue:self.pswTF.text forKey:@"password"];
    [dic setValue:self.V_CodeTF.text.length?self.V_CodeTF.text:@"" forKey:@"smsCode"];
    [dic setValue:self.invitationCodeTF.text forKey:@"referralCode"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_RGISTER_API];
    
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        self.registerBtn.userInteractionEnabled = YES;

        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * code = [data valueForKey:@"code"];
            
            NSDictionary *resultDic = [data valueForKey:@"data"];
            if ([resultDic isKindOfClass:[NSDictionary class]]) {
                if ([code isEqualToString:@"200"]) {
                    
                    [weakSelf.view endEditing:YES];
                    [SVProgressHUD showSuccessWithStatus:@"登录成功"];
                    [SVProgressHUD dismissWithDelay:1];
                    [[TTUserModel sharedObject].userModelDefault
                     setValue:@"loged" forKey:@"login_status"];
                    
                    [[TTUserModel sharedObject].userModelDefault
                     setValue:[resultDic valueForKey:@"phone"] forKey:@"PP_user_account"];
                    
                    [[TTUserModel sharedObject].userModelDefault
                     setValue:[resultDic valueForKey:@"avatar"] forKey:@"user_icon"];
                    
                    [[TTUserModel sharedObject].userModelDefault
                     setValue:[resultDic valueForKey:@"username"] forKey:@"uer_name"];
                    
                    [[TTUserModel sharedObject].userModelDefault
                     setValue:[resultDic valueForKey:@"token"] forKey:@"access_token"];
                    
                    [[TTUserModel sharedObject].userModelDefault
                     setValue:[resultDic valueForKey:@"referralCode"] forKey:@"user_recommandCode"];
                    
                    [[TTUserModel sharedObject].userModelDefault
                     setValue:[resultDic valueForKey:@"id"] forKey:@"uer_id"];
                    
                    [[TTUserModel sharedObject].userModelDefault synchronize];
                    
                    [weakSelf.navigationController dismissViewControllerAnimated:YES completion:nil];
                    
                } else {
                    [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                    [SVProgressHUD dismissWithDelay:1];

                }
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                [SVProgressHUD dismissWithDelay:1];
            }
            
        } else {
            
            [self alert:@"返回为空"];
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        self.registerBtn.userInteractionEnabled = YES;

        [SVProgressHUD showWithStatus:@"请求异常"];
        [SVProgressHUD dismissWithDelay:1];
    }];
}

#pragma mark 注册
- (IBAction)registerUser:(id)sender {
    
    if (!self.phoneNumTF.text.length) {
        
        if (![Utilities checkPhoneTel:self.phoneNumTF.text]) {
            
            [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号"];
            [self.phoneNumTF becomeFirstResponder];
        }
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号"];
        [self.phoneNumTF becomeFirstResponder];
        
    } else {
        
        if (!self.V_CodeTF.text.length) {
            
            [SVProgressHUD showErrorWithStatus:@"请输入验证码"];
            [self.V_CodeTF becomeFirstResponder];
        } else {
            
            if (!self.pswTF.text.length) {
                
                [SVProgressHUD showErrorWithStatus:@"请输入密码"];
                [self.pswTF becomeFirstResponder];
            } else {
                
                if (![self.pswTF.text isEqualToString:self.confirmPswTF.text]) {
                    
                    [SVProgressHUD showErrorWithStatus:@"两次输入密码不一致"];
                    [self.confirmPswTF becomeFirstResponder];
                    
                    return;
                } else {
                    
                }
            }
        }
    }
    
    [SVProgressHUD dismissWithDelay:0.5];

    
    if (!self.isAgree) {
        [SVProgressHUD showErrorWithStatus:@"请同意《用户协议与隐私政策》"];
        return;
    }
    
    
    
    [self request_Register];
    
    //请求接口再做处理
}

- (void)checkTextField {
    

}

- (void)initView {
    
    self.title = @"注册";
    [self.phoneNumTF becomeFirstResponder];
    
    self.isAgree = NO;
    
    self.phoneNumTF.delegate = self;
    
    [self.pswTF setSecureTextEntry:YES];
    [self.confirmPswTF setSecureTextEntry:YES];
    
    self.getVertificationBtn.layer.borderWidth = 1;
    self.getVertificationBtn.layer.borderColor = PP_Default_Color_Red_FF3737.CGColor;
    self.getVertificationBtn.layer.cornerRadius = 4;
    
    [self.agreeBtn setImage:[UIImage imageNamed:@"empty_bg"] forState:UIControlStateNormal];
    
    self.protocolLab.userInteractionEnabled = YES;
    UITapGestureRecognizer* singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goHtml)];
    [self.protocolLab addGestureRecognizer:singleTap];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (textField == self.phoneNumTF) {
        // 这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
        if (range.length == 1 && string.length == 0) {
            
            return YES;
            
        }  else if (self.phoneNumTF.text.length >= 11) {
            
            self.phoneNumTF.text = [textField.text substringToIndex:11];
            
            [SVProgressHUD showInfoWithStatus:@"手机号为11为数字"];
            [SVProgressHUD dismissWithDelay:0.5];
            
            return NO;
        }
    }
    
    if (textField == self.pswTF) {
        NSString*toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        if(textField ==self.pswTF && textField.isSecureTextEntry) {
            
            textField.text= toBeString;
            return NO;
        }
    }
    
    return YES;
}

@end
